// src/layout/Index.jsx

import React, { useState } from 'react';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  HomeOutlined,
  LineChartOutlined,
  MoneyCollectOutlined,
  BulbOutlined,
  EditOutlined,
  RollbackOutlined,
  CopyrightOutlined,
  GithubOutlined,
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
} from '@ant-design/icons';
import { Breadcrumb, Layout, Menu, Avatar, Tooltip, Dropdown } from 'antd';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { $userLogout } from '../../api/userApi';
import Logo from '../../assets/img/logo.png';
import { Button } from 'antd';
import './Index.scss';

const { Header, Content, Sider, Footer } = Layout;

const Index = () => {
  const userInfo = JSON.parse(localStorage.getItem('user_info'));
  const navigate = useNavigate();
  const location = useLocation();

  // 是否折叠侧边栏
  const [collapsed, setCollapsed] = useState(false);

  const handleLogoutMenuItemClick = async () => {
    await $userLogout();
    navigate('/login', { replace: true });
  };

  const dropdownMenuItems = [
    {
      key: 'my_account',
      label: '我的账户',
      icon: <UserOutlined />,
      onClick: () => navigate('/user-info'),
    },
    { type: 'divider' },
    {
      key: 'settings',
      label: '设置',
      icon: <SettingOutlined />,
      onClick: () => navigate('/settings'),
    },
    {
      key: 'logout',
      label: '注销',
      icon: <LogoutOutlined />,
      onClick: handleLogoutMenuItemClick,
    },
  ];

  // 辅助封装菜单项
  const getItem = (label, key, icon, children = null) => ({
    key,
    icon,
    children,
    label,
  });

  const siderMenuItems = [
    getItem('首页', '/home', <HomeOutlined />),
    getItem('新闻资讯', '/news', <LineChartOutlined />),
    getItem('交易策略', '/strategy', <BulbOutlined />, [
      getItem('策略管理', '/strategy/manage', <EditOutlined />),
      getItem('回测策略', '/strategy/backtest', <RollbackOutlined />),
    ]),
    getItem('股票行情', '/stock', <LineChartOutlined />, [
      getItem('股票列表', '/stock/list', <LineChartOutlined />),
      getItem('股票分时图', '/stock/a_minute', <LineChartOutlined />),
      getItem('实时预测', '/predict', <LineChartOutlined />),
      getItem('因子分析', '/stock/alpha', <LineChartOutlined />),
    ]),
    getItem('基金列表', '/fund/list', <LineChartOutlined />),
    getItem('外汇列表', '/forex/spot_list', <LineChartOutlined />),
    getItem('债券列表', '/bond/list', <MoneyCollectOutlined />),
    getItem('交易信息', '/transaction/list', <MoneyCollectOutlined />),
    getItem('资产管理', '/asset', <EditOutlined />),
    getItem('关于', '/about', <CopyrightOutlined />),
    getItem('风险评估', '/risk', <EditOutlined />,[
      getItem('风险评估', '/risk/scores', <EditOutlined />),
      getItem('股票持仓风险分析', '/risk/stock_scores', <EditOutlined />),
    ]),
  ];

  // 扁平化菜单映射，便于生成面包屑
  const flattenMenuItems = (items) => {
    let map = {};
    items.forEach((item) => {
      map[item.key] = item;
      if (item.children) {
        map = { ...map, ...flattenMenuItems(item.children) };
      }
    });
    return map;
  };
  const menuItemsMap = flattenMenuItems(siderMenuItems);

  const [breadcrumbItems, setBreadcrumbItems] = React.useState([
    { title: '首页' },
  ]);

  const handleMenuItemClick = (e) => {
    const { keyPath } = e; // keyPath 从子到父
    const updated = keyPath
      .slice()
      .reverse()
      .map((key) => ({ title: menuItemsMap[key].label }));
    setBreadcrumbItems(updated);
    navigate(e.key);
  };

  // 切换侧边栏折叠
  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };

  return (
    <Layout className="home-layout">
      <Header className="header">
        <div className="header-left">
          <Button
            type="text"
            className="collapse-trigger"
            onClick={toggleCollapsed}
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          />
          <img className="logo" src={Logo} alt="logo" />
          {!collapsed && (
            <div className="title">Intelli Whale 智能投顾平台
            </div>
          )}
        </div>
        <div className="header-right">
          <Avatar size={42} icon={<UserOutlined />} className="avatar" />
          <Dropdown menu={{ items: dropdownMenuItems }} trigger={['click']}>
            <Tooltip placement="left" title={userInfo.nickname}>
              <span className="nickname">{userInfo.nickname}</span>
            </Tooltip>
          </Dropdown>
        </div>
      </Header>

      <Layout>
        <Sider
          width={220}
          collapsible
          collapsed={collapsed}
          trigger={null}
          className="sider"
        >
          <Menu
            mode="inline"
            selectedKeys={[location.pathname]}
            className="sider-menu"
            items={siderMenuItems}
            onClick={handleMenuItemClick}
          />
        </Sider>

        <Layout className="content-layout">
          <Content className="content">
            <Outlet />
          </Content>
          <Footer className="footer">
            <GithubOutlined className="footer-icon" /> Copyright{' '}
            <CopyrightOutlined /> 2025 NJU金融软工项目 ZZLD小组
          </Footer>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default Index;
